package com.wkbb.basic.controller.open;

import com.qiniu.util.Auth;
import com.wkbb.basic.service.DistrictService;
import com.wkbb.basic.service.NationalityService;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.*;
import com.wkbb.common.enums.ButtonTypeEnum;
import com.wkbb.common.enums.CompanyTypeEnum;
import com.wkbb.common.enums.OrganizationTypeEnum;
import com.wkbb.common.enums.SchoolTypeEnum;
import com.wkbb.common.redis.IMRedisTemplateUtil;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.redis.WxRedisTemplateUtil;
import com.wkbb.common.utils.DateUtil;
import com.wkbb.common.utils.QiniuUtil;
import com.wkbb.common.utils.ShortUrlUtil;
import com.wkbb.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 基础模块对外接口
 */
@RestController
@Api(description = "公共模块对外接口")
@RequestMapping("/basic/{apiVersion}/open")
@Slf4j
public class CommonController extends BaseController {

    @Autowired
    private DistrictService districtService;

    @Autowired
    private NationalityService nationalityService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private WxRedisTemplateUtil wxRedisTemplateUtil;

    @Autowired
    private IMRedisTemplateUtil imRedisTemplateUtil;


    @ApiOperation(value = "获取七牛上传凭证")
    @GetMapping(value = "getQiniuUpToken")
    public ResultDTO<String> getQiniuUpToken(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion){
        UserDto userDto = this.getUserByLogin();
        if(null == userDto) {
            return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
        }
        String upToken = QiniuUtil.getInstance().getToken();
        return new ResultDTO<>(upToken);
    }

    @ApiOperation(value = "获取系统当前时间(毫秒数)")
    @GetMapping(value = "getSystemTime")
    public ResultDTO<Long> getSystemTime(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion){
        try{
            return new ResultDTO<Long>(System.currentTimeMillis());
        }catch (Exception e){
            log.error("获取系统当前时间(getSystemTime)接口异常:",e);
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "组织类型")
    @RequestMapping(value = "/getOrgTypeList", method = RequestMethod.GET)
    public ResultDTO<List<OrgTypeDto>> getOrgTypeList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion)
    {
            List<OrgTypeDto> list = new ArrayList<OrgTypeDto>();
            for(OrganizationTypeEnum typeEnum : OrganizationTypeEnum .values()){
                if (typeEnum.getValue() > 4){
                    OrgTypeDto orgTypeDto = new OrgTypeDto();
                    orgTypeDto.setOrgTypeId(typeEnum.getValue());
                    orgTypeDto.setOrgTypeName(typeEnum.getDesc());
                    list.add(orgTypeDto);
                }
            }
            return new ResultDTO<List<OrgTypeDto>>(list);
    }

    @ApiOperation(value = "学校类型")
    @RequestMapping(value = "/getSchoolTypeList", method = RequestMethod.GET)
    public ResultDTO<List<OrgTypeDto>> getSchoolTypeList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion)
    {
        List<OrgTypeDto> list = new ArrayList<OrgTypeDto>();
        for(SchoolTypeEnum typeEnum : SchoolTypeEnum.values()){
            OrgTypeDto orgTypeDto = new OrgTypeDto();
            orgTypeDto.setOrgTypeId(typeEnum.getValue());
            orgTypeDto.setOrgTypeName(typeEnum.getDesc());

            list.add(orgTypeDto);
        }

        return new ResultDTO<List<OrgTypeDto>>(list);
    }

    @ApiOperation(value = "企业类型")
    @RequestMapping(value = "/getCompanyTypeList", method = RequestMethod.GET)
    public ResultDTO<List<OrgTypeDto>> getCompanyTypeList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion)
    {
        List<OrgTypeDto> list = new ArrayList<OrgTypeDto>();
        for(CompanyTypeEnum typeEnum : CompanyTypeEnum.values()){
            OrgTypeDto orgTypeDto = new OrgTypeDto();
            orgTypeDto.setOrgTypeId(typeEnum.getValue());
            orgTypeDto.setOrgTypeName(typeEnum.getDesc());

            list.add(orgTypeDto);
        }

        return new ResultDTO<List<OrgTypeDto>>(list);
    }

    @ApiOperation(value = "查询省份/城市/(县/镇)列表")
    @RequestMapping(value = "/getDistrictList", method = RequestMethod.GET)
    public ResultDTO<List<DistrictDto>> getDistrictList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "parentCode(获取省份parentCode填0)", required = true) @RequestParam(name = "parentCode", required = true) Integer parentCode,
            @ApiParam(value = "type(城市的类型，0国家，1省份，2城市，3区镇)", required = true) @RequestParam(name = "type", required = true) Integer type){

        if (null==parentCode || null==type) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
        List<DistrictDto> districtList = null;
        try {
            districtList = districtService.getDistrictList(parentCode,type);
        }catch (Exception e){
            log.error("查询省份/城市/(县/镇)列表(getDistrictList)接口异常:",e);
        }
        return new ResultDTO<List<DistrictDto>>(districtList);
    }

    @ApiOperation(value = "根据名称查询省份/城市/(县/镇)")
    @RequestMapping(value = "/findDistrict", method = RequestMethod.GET)
    public ResultDTO<DistrictDto> findDistrict(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "名称", required = true) @RequestParam(name = "name", required = true) String name,
            @ApiParam(value = "type(城市的类型，0国家，1省份，2城市，3区镇)", required = true) @RequestParam(name = "type", required = true) Integer type){
        DistrictDto districtDto = districtService.findDistrict(name,type);;
        if (districtDto == null){
            return new ResultDTO<>(ErrorCode.NOT_DATA);
        }
        return new ResultDTO<>(districtDto);
    }

    @ApiOperation(value = "查询所有省份/城市/(县/镇)列表")
    @RequestMapping(value = "/getAllDistrictList", method = RequestMethod.GET)
    public ResultDTO<List<DistrictDto>> getAllDistrictList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion)
    {
        List<DistrictDto> allDistrictList = new ArrayList<>();
        try {
            //获取省份
            List<DistrictDto> provinceList = districtService.getDistrictList(0,1);
            for(DistrictDto province : provinceList)
            {
                List<DistrictDto> cityList = districtService.getDistrictList(province.getCode(),2);
               // province.setChildList(cityList);

                allDistrictList.add(province);
            }
        }catch (Exception e){
            log.error("查询省份/城市/(县/镇)列表(getDistrictList)接口异常:",e);
        }
        return new ResultDTO<List<DistrictDto>>(allDistrictList);
    }

    @ApiOperation(value = "查询民族列表")
    @RequestMapping(value = "/getNationalityList", method = RequestMethod.GET)
    public ResultDTO<List<NationalityDto>> getNationalityList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion){
        List<NationalityDto> nationalityList = null;
        try {
            nationalityList = nationalityService.getNationalityList();
        }catch (Exception e){
            log.error("查询民族列表(getNationalityList)接口异常:",e);
        }
        return new ResultDTO<List<NationalityDto>>(nationalityList);
    }

    @ApiOperation(value = "权限按钮列表")
    @RequestMapping(value = "/getButtonList", method = RequestMethod.GET)
    public ResultDTO<List<ButtonTypeDto>> getButtonList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion)
    {
        List<ButtonTypeDto> list = new ArrayList<ButtonTypeDto>();
        for(ButtonTypeEnum typeEnum : ButtonTypeEnum .values()){
            ButtonTypeDto buttonTypeDto = new ButtonTypeDto();
            buttonTypeDto.setCode(typeEnum.getValue());
            buttonTypeDto.setName(typeEnum.getDesc());

            list.add(buttonTypeDto);
        }

        return new ResultDTO<List<ButtonTypeDto>>(list);
    }

    @ApiOperation(value = "获取h5版本号")
    @RequestMapping(value = "/getH5Version", method = RequestMethod.GET)
    public ResultDTO<String> getH5Version(
        @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion)
    {
        String version = (String) redisTemplateUtil.get(RedisKeyConstant.WKBB_BASIC_COMMON_H5_VERSION);
        if(StringUtil.isEmpty(version)){
            version = "V" + DateUtil.toDayMinString(new Date());
        }
        return new ResultDTO<>(version);
    }

    @ApiOperation(value = "设置h5版本号")
    @RequestMapping(value = "/setH5Version", method = RequestMethod.POST)
    public ResultDTO<String> setH5Version(
        @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
        @ApiParam(value = "版本号", required = true) @RequestParam(name = "version", required = true) String version
    ){

        try {
            redisTemplateUtil.set(RedisKeyConstant.WKBB_BASIC_COMMON_H5_VERSION, version);
        }catch (Exception e){
            log.error("设置h5版本号接口异常:{}", e);
        }
        return new ResultDTO<>(true);
    }

    @ApiOperation(value = "设置短链接地址")
    @RequestMapping(value = "/setDwzUrl", method = RequestMethod.POST)
    public ResultDTO<String> setDwzUrl(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "长链接", required = false) @RequestParam(name = "longUrl", required = false) String longUrl
    ){

        try {

            if(StringUtils.isEmpty(longUrl))
            {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            //设置短链接
            String dwzShortUrl = ShortUrlUtil.getShortUrl(longUrl);
            String redisKey = RedisKeyConstant.WKBB_BASIC_COMMON_DWZ + dwzShortUrl;
            redisTemplateUtil.set(redisKey,longUrl,RedisKeyConstant.EXPIRATION_TIME_HALF_YEAR);
            return new ResultDTO<>(dwzShortUrl);
        }catch (Exception e){
            log.error("设置短链接地址:{}", e);
        }
        return new ResultDTO<>(true);
    }

    @ApiOperation(value = "获取长链接地址")
    @RequestMapping(value = "/getDwzUrl", method = RequestMethod.GET)
    public ResultDTO<String> getDwzUrl(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "短链接", required = false) @RequestParam(name = "shortUrl", required = false) String shortUrl
    ){

        try {

            if(StringUtils.isEmpty(shortUrl))
            {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            String redisKey = RedisKeyConstant.WKBB_BASIC_COMMON_DWZ + shortUrl;
            String dwzLongUrl = (String) redisTemplateUtil.get(redisKey);
            return new ResultDTO<>(dwzLongUrl);
        }catch (Exception e){
            log.error("获取长链接地址:{}", e);
        }
        return new ResultDTO<>(true);
    }

    @ApiOperation(value = "获取redis值")
    @RequestMapping(value = "/getRedisValue", method = RequestMethod.GET)
    public ResultDTO<Object> getRedisValue(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "redis库", required = true, defaultValue = "2") @RequestParam(name = "redisDb", required = true) String redisDb,
            @ApiParam(value = "是否模糊", required = true, defaultValue = "false") @RequestParam(name = "isLike", required = true) Boolean isLike,
            @ApiParam(value = "redisKey", required = true) @RequestParam(name = "redisKey", required = true) String redisKey)
    {
        try {

            Object object = null;
            if(StringUtils.isNotEmpty(redisKey))
            {
                if("2".equals(redisDb))
                {
                    if(!isLike) {
                        object = redisTemplateUtil.get(redisKey);
                    }
                    else
                    {
                        object = redisTemplateUtil.queryListByKey(redisKey);
                    }
                }
                else if("3".equals(redisDb))
                {
                    if(!isLike) {
                        object = imRedisTemplateUtil.get(redisKey);
                    }
                    else
                    {
                        object = imRedisTemplateUtil.queryListByKey(redisKey);
                    }
                }
                else if("10".equals(redisDb))
                {
                    if(!isLike) {
                        object = wxRedisTemplateUtil.get(redisKey);
                    }
                    else
                    {
                        object = wxRedisTemplateUtil.queryListByKey(redisKey);
                    }
                }

                return new ResultDTO<Object>(object);
            }

        }catch (Exception e){
            log.error("获取redis值:{}", e);
        }
        return new ResultDTO<>(true);
    }

    @ApiOperation(value = "设置redis值")
    @RequestMapping(value = "/setRedisValue", method = RequestMethod.POST)
    public ResultDTO<Object> setRedisValue(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "redis库", required = true, defaultValue = "2") @RequestParam(name = "redisDb", required = true) String redisDb,
            @ApiParam(value = "redisKey", required = true) @RequestParam(name = "redisKey", required = true) String redisKey,
            @ApiParam(value = "redisValue", required = true) @RequestParam(name = "redisValue", required = true) String redisValue,
            @ApiParam(value = "redisTime", required = false) @RequestParam(name = "redisTime", required = false) Long redisTime)
    {
        try {

            if(StringUtils.isNotEmpty(redisKey) && StringUtils.isNotEmpty(redisValue))
            {
                if("2".equals(redisDb))
                {
                    if(null==redisTime) {
                        redisTemplateUtil.set(redisKey,redisValue);
                    }
                    else{
                        redisTemplateUtil.set(redisKey,redisValue,redisTime);
                    }
                }
                else if("3".equals(redisDb))
                {
                    if(null==redisTime) {
                        imRedisTemplateUtil.set(redisKey,redisValue);
                    }
                    else{
                        imRedisTemplateUtil.set(redisKey,redisValue,redisTime);
                    }
                }
                else if("10".equals(redisDb))
                {
                    if(null==redisTime) {
                        wxRedisTemplateUtil.set(redisKey,redisValue);
                    }
                    else{
                        wxRedisTemplateUtil.set(redisKey,redisValue,redisTime);
                    }
                }
            }

        }catch (Exception e){
            log.error("设置redis值:{}", e);
        }
        return new ResultDTO<>(true);
    }

    @ApiOperation(value = "清除redis值")
    @RequestMapping(value = "/delRedisValue", method = RequestMethod.POST)
    public ResultDTO<Object> delRedisValue(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "redis库", required = true, defaultValue = "2") @RequestParam(name = "redisDb", required = true) String redisDb,
            @ApiParam(value = "是否模糊", required = true, defaultValue = "false") @RequestParam(name = "isLike", required = true) Boolean isLike,
            @ApiParam(value = "redisKey", required = true) @RequestParam(name = "redisKey", required = true) String redisKey)
    {
        try {

            if(StringUtils.isNotEmpty(redisKey))
            {
                if("2".equals(redisDb))
                {
                    if(!isLike) {
                        redisTemplateUtil.delete(redisKey);
                    }
                    else{
                        redisTemplateUtil.delKeysLike(redisKey);
                    }
                }
                else if("3".equals(redisDb))
                {
                    if(!isLike) {
                        imRedisTemplateUtil.delete(redisKey);
                    }
                    else{
                        imRedisTemplateUtil.delKeysLike(redisKey);
                    }
                }
                else if("10".equals(redisDb))
                {
                    if(!isLike) {
                        wxRedisTemplateUtil.delete(redisKey);
                    }
                    else{
                        wxRedisTemplateUtil.delKeysLike(redisKey);
                    }
                }
            }

        }catch (Exception e){
            log.error("清除redis值:{}", e);
        }
        return new ResultDTO<>(true);
    }

}
